package com.adkun.community.controller;

import com.adkun.community.entity.DiscussPost;
import com.adkun.community.entity.Page;
import com.adkun.community.service.ElasticsearchService;
import com.adkun.community.service.LikeService;
import com.adkun.community.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.adkun.community.util.CommunityConstants.ENTITY_TYPE_POST;

@Controller
public class SearchController {

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    /**
     * 搜索功能
     * search?keyword=xxx
     *
     * @param keyword
     * @param page
     * @param model
     * @return
     */
    @RequestMapping(path = "/search", method = RequestMethod.GET)
    public String search(String keyword, Page page, Model model) {
        // 搜索帖子
        Map<String, Object> searchResult =
                elasticsearchService.searchDiscussPost(keyword, page.getCurrent() - 1, page.getLimit()); // 由于Page里面的current是自然顺序，所以需要-1

        List<DiscussPost> discussPosts = (List<DiscussPost>) searchResult.get("posts");
        List<Map<String, Object>> discussVo = new ArrayList<>();
        if (discussPosts != null) {
            for (DiscussPost post : discussPosts) {
                Map<String, Object> map = new HashMap<>();
                // 帖子
                map.put("post", post);
                // 作者
                map.put("user", userService.findUserById(post.getUserId()));
                // 点赞数量
                map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId()));

                discussVo.add(map);
            }
        }
        model.addAttribute("discussPosts", discussVo);
        model.addAttribute("keyword", keyword);

        // 分页信息
        page.setPath("/search?keyword=" + keyword);
        page.setRows((int) searchResult.get("hitsCount"));

        return "/site/search";
    }
}
